export class MsgDispatcher  {

    static instance: MsgDispatcher;

    static getInstance(): MsgDispatcher
    {
        if(MsgDispatcher.instance == null)
        {
            MsgDispatcher.instance = new MsgDispatcher();
        }

        return MsgDispatcher.instance;
    }

    msgDispatcher: {[key:number]: ((param: any[]) => void)[]} = {}

    registerMsg(msgID: number, handler: (restParam: any[]) => void): void
    {
        let msgHandler = this.msgDispatcher[msgID];
        if(msgHandler == undefined)
        {
            this.msgDispatcher[msgID] = [handler];
        }
        else
        {
            msgHandler.push(handler);
        }
    }

    unregisterMsg(msgID: number, handler: (restParam: any[]) => void): void
    {
        let msgHandler = this.msgDispatcher[msgID];
        if(msgHandler != undefined)
        {
            for(let i = 0; i < msgHandler.length; i++)
            {
                if(msgHandler[i] == handler)
                {
                    msgHandler[i] = null;
                }
            }
        }
    }

    dispatchMsg(msgID: number, restParam: any[]): void
    {
        let msgHandler = this.msgDispatcher[msgID];
        if(msgHandler != undefined)
        {
            for(let i = 0; i < msgHandler.length; i++)
            {
                if(msgHandler[i] != null)
                {
                    msgHandler[i](restParam);
                }
            }
        }
    }
}
